package com.myz.springboot2.scan.config;

import org.reflections.Reflections;
import org.reflections.scanners.MethodAnnotationsScanner;
import org.reflections.scanners.Scanners;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author maoyz0621
 */
@Configuration
public class ScanBean {

    private final Map<Class<?>, Object> beanMap = new ConcurrentHashMap<>();
    String packageName = "com.myz.springboot2";

    @PostConstruct
    public void scanGenerateBean() {
        Reflections reflections = new Reflections(packageName);
        // 扫描指定的类及子类
        Set<Class<?>> subTypesOf = reflections.getSubTypesOf(Object.class);
        for (Class<?> aClass : subTypesOf) {
            System.out.println(aClass);
        }

        // 扫描注解的类
        Set<Class<?>> typesAnnotatedWith = reflections.getTypesAnnotatedWith(Configuration.class);
        for (Class<?> aClass : typesAnnotatedWith) {
            System.out.println(aClass);
        }

        // 扫描注解的方法
        Set<Method> methodsAnnotatedWith = reflections.getMethodsAnnotatedWith(PostConstruct.class);
        for (Method method : methodsAnnotatedWith) {
            System.out.println(method);
        }


        Reflections reflectionsMethod = new Reflections(new ConfigurationBuilder()
                .setUrls(ClasspathHelper.forPackage(packageName))
                .addScanners(Scanners.MethodsAnnotated));

        // 扫描注解的方法
        Set<Method> methodsAnnotatedWith1 = reflectionsMethod.getMethodsAnnotatedWith(PostConstruct.class);
        for (Method method : methodsAnnotatedWith1) {
            System.out.println(method);
        }
    }
}
